<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="原料id" prop="materialId">
        <el-input
          v-model="queryParams.materialId"
          placeholder="请输入原料id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货品原料种类" prop="materialKind">
        <el-input
          v-model="queryParams.materialKind"
          placeholder="请输入货品原料种类"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货品原料数量" prop="materialNum">
        <el-input
          v-model="queryParams.materialNum"
          placeholder="请输入货品原料数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="加工开始时间" prop="startTime">
        <el-date-picker clearable
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择加工开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="加工结束时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择加工结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="加工状态" prop="processState">
        <el-input
          v-model="queryParams.processState"
          placeholder="请输入加工状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['storage:processRecord:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['storage:processRecord:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['storage:processRecord:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['storage:processRecord:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="processRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="加工单id" align="center" prop="processId" />
      <el-table-column label="原料id" align="center" prop="materialId" />
      <el-table-column label="货品原料种类" align="center" prop="materialKind" />
      <el-table-column label="货品原料数量" align="center" prop="materialNum" />
      <el-table-column label="加工开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加工结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="加工状态" align="center" prop="processState" />
      <el-table-column label="创建者" align="center" prop="generatedBy" />
      <el-table-column label="加工说明" align="center" prop="processDescription" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['storage:processRecord:edit']"
            :disabled="scope.row.processState === '已完成'"
          >完善加工信息</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['storage:processRecord:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改加工单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item v-if="!showProcessingDetails" label="原料种类" prop="materialId">
          <el-select v-model="form.materialId" placeholder="请选择原料种类">
            <el-option label="牛肉" value="6666" />
            <el-option label="羊肉" value="7777" />
            <el-option label="其他" value="8888" />
          </el-select>
        </el-form-item>
        <!--   添加可增加行的多行输入框     -->
        <template v-if="!showProcessingDetails">
        <el-divider content-position="center">逐件输入原料的货品编码</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddMaterial">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" >扫码录入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteMaterial">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="materialList" @selection-change="handleMaterialSelectionChange" ref="materialTable">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="货品编码" prop="code" width="150">
            <template slot-scope="scope">
              <el-input v-model="materialList[scope.$index]" placeholder="请输入货品编码" />
            </template>
          </el-table-column>
        </el-table>
        </template>


        <el-form-item v-if="!showProcessingDetails" label="加工说明" prop="processDescription">
          <el-input v-model="form.processDescription" placeholder="请输入加工说明" />
        </el-form-item>

        <!-- 使用 v-if 控制加工详情信息的显示 -->
        <template v-if="showProcessingDetails">
        <el-divider content-position="center">加工详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddProcessingDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteProcessingDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="processingDetailList" :row-class-name="rowProcessingDetailIndex" @selection-change="handleProcessingDetailSelectionChange" ref="processingDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
<!--          <el-table-column label="产物商品id" prop="processedProductId" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.processedProductId" placeholder="请输入产物商品id" />-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="商品名称" prop="inventoryName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.inventoryName" placeholder="请输入该批商品名称" />
            </template>
          </el-table-column>
          <el-table-column label="种类id" prop="rawProductId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.rawProductId" placeholder="请输入种类" />
            </template>
          </el-table-column>
          <el-table-column label="包装方式" prop="packingType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.packingType" placeholder="请选择包装方式">
                <el-option label="盒装" value="盒装" />
                <el-option label="袋装" value="袋装" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="物品规格" prop="goodSpecification" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.goodSpecification" placeholder="请选择物品规格">
                <el-option label="500g/盒" value="500g/盒" />
                <el-option label="500g/包" value="500g/包" />
                <el-option label="1000g/盒" value="1000g/盒" />
                <el-option label="1000g/包" value="1000g/包" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="inventoryNum" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.inventoryNum" placeholder="请输入数量" />
            </template>
          </el-table-column>
<!--          <el-table-column label="商品状态" prop="productState" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.productState" placeholder="请输入商品状态" />-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="加工说明" prop="processDescription" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.processDescription" placeholder="请输入加工说明" />
            </template>
          </el-table-column>
        </el-table>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProcessRecord, getProcessRecord, delProcessRecord, addProcessRecord, updateProcessRecord } from "@/api/storage/processRecord";

export default {
  name: "ProcessRecord",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedProcessingDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 加工单管理表格数据
      processRecordList: [],
      // 加工详情表格数据
      processingDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      showProcessingDetails: false, // 新增标志变量
      materialList: [], // 初始化为空数组
      checkedMaterials: [], // 用于存储选中的货品编码
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        salesId: null,
        materialId: null,
        materialKind: null,
        materialNum: null,
        startTime: null,
        endTime: null,
        processState: null,
        generatedBy: null
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        materialId: [
          { required: true, message: "原料id不能为空", trigger: "blur" }
        ],

      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询加工单管理列表 */
    getList() {
      this.loading = true;
      listProcessRecord(this.queryParams).then(response => {
        this.processRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        processId: null,
        salesId: null,
        materialId: null,
        warehouseId: null,
        materialKind: null,
        materialNum: null,
        startTime: null,
        endTime: null,
        processState: null,
        generatedBy: null
      };
      this.processingDetailList = [];
      this.materialList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.processId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加加工单管理";
      this.showProcessingDetails = false; // 隐藏加工详情信息

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (row.processState === '已完成') {
        this.$modal.msgWarning('该加工单的状态为“已完成”，无法进行修改。');
        return;
      }
      this.reset();
      const processId = row.processId || this.ids
      getProcessRecord(processId).then(response => {
        this.form = response.data;
        this.processingDetailList = response.data.processingDetailList;
        this.open = true;
        this.title = "修改加工单管理";
        this.showProcessingDetails = true; // 显示加工详情信息

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.processingDetailList = this.processingDetailList;
          this.form.materialList = this.materialList;
          if (this.form.processId != null) {
            updateProcessRecord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProcessRecord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const processIds = row.processId || this.ids;
      this.$modal.confirm('是否确认删除加工单管理编号为"' + processIds + '"的数据项？').then(function() {
        return delProcessRecord(processIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 加工详情序号 */
    rowProcessingDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 加工详情添加按钮操作 */
    handleAddProcessingDetail() {
      let obj = {};
      obj.processedProductId = "";
      obj.packingType = "";
      obj.productState = "";
      obj.processDescription = "";
      this.processingDetailList.push(obj);
    },
    /** 加工详情删除按钮操作 */
    handleDeleteProcessingDetail() {
      if (this.checkedProcessingDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的加工详情数据");
      } else {
        const processingDetailList = this.processingDetailList;
        const checkedProcessingDetail = this.checkedProcessingDetail;
        this.processingDetailList = processingDetailList.filter(function(item) {
          return checkedProcessingDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleProcessingDetailSelectionChange(selection) {
      this.checkedProcessingDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('storage/processRecord/export', {
        ...this.queryParams
      }, `processRecord_${new Date().getTime()}.xlsx`)
    },
    /** 货品编码序号 */
    rowMaterialIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 货品编码添加按钮操作 */
    handleAddMaterial() {
      this.materialList.push("");
    },
    /** 货品编码删除按钮操作 */
    handleDeleteMaterial() {
      if (this.checkedMaterials.length == 0) {
        this.$modal.msgError("请先选择要删除的货品编码");
      } else {
        this.materialList = this.materialList.filter((_, index) => !this.checkedMaterials.includes(index));
        this.checkedMaterials = [];
      }
    },
    /** 复选框选中数据 */
    handleMaterialSelectionChange(selection) {
      this.checkedMaterials = selection.map(item => this.materialList.indexOf(item));

    },
  }
};
</script>
